package broth.gdt;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.location.Location;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Projection;

public class MyLocationOverlayCompass extends MyLocationOverlay {

	Drawable icon;
	Resources res;
	Rect rect;
	Projection projection;
	Point point;
	float accuracy;
	float orientation;
	MapView mMapView;
	Paint paint;
	
	// get the icon resources and map view
	public MyLocationOverlayCompass(Context context, MapView mapView, Resources resources) {
		super(context, mapView);
		res = resources;
		mMapView = mapView;
	}
	
	// called when the compass sensor changes
	public void onSensorChanged(int sensor, float[] values) {
		super.onSensorChanged(sensor, values);
		
		mMapView.postInvalidate();
	}
	
	// called to draw the compass with bearing
	protected void drawCompass(Canvas canvas, float bearing) {
		// compass bearing is included in location icon
	}
	
	// draw the location icon (with compass bearing and accuracy)
	protected void drawMyLocation(Canvas canvas, MapView mapView, Location lastFix, GeoPoint myLocation, long when) {
		
		// get the icon resources
		icon = res.getDrawable(R.drawable.androidmarker);
		
		// convert the current view to pixel numbers
		projection = mapView.getProjection();
		point = projection.toPixels(myLocation, null);
		
		// create a location and size for the location marker
		rect = new Rect(point.x-18, point.y-25, point.x+18, point.y+25);
		icon.setBounds(rect);
		
		// save the current canvas state
		canvas.save();
		
		// get the accuracy in pixels from the last location update
		accuracy = projection.metersToEquatorPixels(lastFix.getAccuracy());
		
		// generate a paint to use
		paint = new Paint();
		paint.setAntiAlias(false);
		paint.setStyle(Paint.Style.FILL);
		paint.setARGB(30, 164, 198, 57);
		
		// draw a circle around the location for the accuracy
		canvas.drawCircle(point.x, point.y, accuracy, paint);
		
		// get the compass bearing
		orientation = getOrientation();
		
		// if a compass bearing is known
		if(!Float.isNaN(orientation)) {
			
			// rotate the canvas around the location to show bearing
			canvas.rotate(orientation, point.x, point.y);
		}
		
		// draw the icon with the canvas rotated
		icon.draw(canvas);
		
		// restore the canvas (undo rotation)
		canvas.restore();
	}
	
}
